<?php

	namespace org\tekuna\plugin\simplesecurity\action;
	
	use org\tekuna\framework\response\http\RelativeRedirectResponse;

	use org\tekuna\framework\action\ActionEvent;
	use org\tekuna\framework\request\Request;
	use org\tekuna\framework\response\http\UrlRedirectResponse;
	use org\tekuna\framework\filter\data\FrameworkActionFilter;
	use org\tekuna\framework\filter\data\AlphanumericCharsFilter;
	use org\tekuna\framework\filter\data\PrintableCharsFilter;
	
	use org\tekuna\plugin\simplesecurity\SecurityManager;
	use org\tekuna\plugin\simplesecurity\SecurityException;
	use org\tekuna\plugin\simpletemplate\SimpleTemplateAction;
	
	class LoginAction extends SimpleTemplateAction {
		
		protected
			$objSecurityManager,
			
			$errorMessage = '',
			$loginUrl;
		
		public function executeTemplate(ActionEvent $objActionEvent, Request $objRequest) {
		
			// get the unauthorized action
			$objRequest -> setGetFilter('unauthorizedAction', new FrameworkActionFilter());

			// try to authenticate when form was submitted
			if ($objRequest -> hasPostValue('login')) {
				
				$objRequest -> setPostFilter('login', new AlphanumericCharsFilter());
				$objRequest -> setPostFilter('password', new PrintableCharsFilter());
				
				$sLogin = $objRequest -> getPostValue('login');
				$sPassword = $objRequest -> getPostValue('password');
				
				try {
					
					$this -> objSecurityManager -> loginUser($sLogin, $sPassword);
				
					// send redirect
					if ($objRequest -> hasGetValue('unauthorizedAction')) {
						
						// redirect to previously unauthorized action
						$objRedirectUrl = $objActionEvent -> buildActionUrl($objRequest -> getGetValue('unauthorizedAction'));
						return new UrlRedirectResponse($objRedirectUrl);
					}
					else {
						
						// redirect to default after login action
						$objRedirectUrl = $objActionEvent -> buildActionUrl($this -> objSecurityManager -> getAfterLoginAction());
						return new UrlRedirectResponse($objRedirectUrl);
					}
				}
				catch (SecurityException $objException) {
					
					$this -> errorMessage = 'The login was not successful.';
				}
			}
			
			// self link
			$this -> loginUrl = $objRequest -> buildCurrentRequestUrl();
		}
		
		
		public function setSimpleSecurityManager(SecurityManager $objSecurityManager) {
			
			$this -> objSecurityManager = $objSecurityManager;
		}
	}